package com.socialuni.sdk.service.comment;

import com.socialuni.sdk.constant.UserType;
import com.socialuni.sdk.exception.SocialParamsException;
import com.socialuni.sdk.model.DO.comment.CommentDO;
import com.socialuni.sdk.model.DO.talk.TalkDO;
import com.socialuni.sdk.model.DO.user.UserDO;
import com.socialuni.sdk.model.QO.comment.CommentAddVO;
import com.socialuni.sdk.repository.CommentRepository;
import com.socialuni.sdk.repository.TalkRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.Optional;

/**
 * @author qinkaiyuan
 * @date 2018-09-16 18:35
 */
@Service
public class CommentCheckService {

    @Resource
    private EntityManager entityManager;

    @Resource
    private CommentRepository commentRepository;

    @Resource
    private TalkRepository talkRepository;

    @Resource
    private ModelContentCheck modelContentCheck;

  /*  @Resource
    CommentRepository comRep;

    public List<Comment> queryCommentList() {
        List<Comment> comments = comRep.findAllByTalk(new Talk(15));
        return comments;
    }*/

    //校验添加新增comment的评论是否正确
    public CommentAddLineTransfer checkCommentAddVO(CommentAddVO addVO, UserDO requestUser) {
        //校验内容是否违规
         modelContentCheck.checkUserAndContent(addVO.getContent(),requestUser);


        //因为与下面有关联所以拿到了上面
        Optional<TalkDO> talkOptional = talkRepository.findById(addVO.getTalkId());
        if (!talkOptional.isPresent()) {
            throw new SocialParamsException("无法评论不存在的动态");
        }
        TalkDO talkDO = talkOptional.get();
        //不为系统用户才校验
        if (!UserType.system.equals(requestUser.getType())) {
            if (!ObjectUtils.isEmpty(talkDO.getGlobalTop()) && talkDO.getGlobalTop() > 0) {
                throw new SocialParamsException("禁止评论官方置顶");
            }
        }

        CommentDO parentCommentDO = null;
        if (addVO.getCommentId() != null) {
            Optional<CommentDO> commentOptional = commentRepository.findById(addVO.getCommentId());
            if (!commentOptional.isPresent()) {
                throw new SocialParamsException("无法回复不存在的评论");
            }
            parentCommentDO = commentOptional.get();
        }
        //得到回复的评论
        CommentDO replyCommentDO = null;
        if (addVO.getReplyCommentId() != null) {
            Optional<CommentDO> replyCommentOptional = commentRepository.findById(addVO.getReplyCommentId());
            if (!replyCommentOptional.isPresent()) {
                throw new SocialParamsException("无法回复不存在的子评论");
            }
            replyCommentDO = replyCommentOptional.get();
        }
        return new CommentAddLineTransfer(talkDO, parentCommentDO, replyCommentDO);
    }
}
